package com.pt25.base.web;


import com.pt25.base.constants.BaseConstants;
import com.pt25.base.util.StrUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.slf4j.MDC;
import org.springframework.lang.Nullable;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.UUID;


/**
 * web请求拦截器
 * 1、获取header头中的traceId
 * 2、获取header头中的rpc token信息
 * 3、获取header头中的tenantId
 */
@Slf4j
public class WebInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, @NotNull HttpServletResponse response, @NotNull Object handler) {
        WebSession webSession = WebSession.builder().build();
        //获取header头中租户id
        String tenantId = request.getHeader(BaseConstants.X_TENANT_ID);
        webSession.setTenantId(StrUtil.isNotBlank(tenantId) ? tenantId : "0");
        //获取header头中rpc token
        String rpcToken = request.getHeader(BaseConstants.X_RPC_TOKEN);
        webSession.setRpcToken(rpcToken);
        //获取header头中链路追踪id
        String traceId = request.getHeader(BaseConstants.X_TRACE_ID);
        webSession.setTraceId(StrUtil.isBlank(traceId) ? generateTraceId() : traceId);
        //添加traceId，在logback配置文件串添加traceId配置会自动输出traceId
        MDC.put("traceId", webSession.getTraceId());
        MDC.put("tenantId", webSession.getTenantId());
        //将sessionInfo保存到本地线程上下文中
        WebThreadLocal.set(webSession);
        return true;
    }


    @Override
    public void afterCompletion(@NotNull HttpServletRequest request, @NotNull HttpServletResponse response, @NotNull Object handler, @Nullable Exception ex) {
        WebThreadLocal.clean();
        MDC.clear();
    }

    private static String generateTraceId() {
        return UUID.randomUUID().toString().replace("-", "").substring(0, 16);
    }
}